<template>
  <div class="message-page">
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">我的消息</h2>
        <el-button type="primary" @click="markAllAsRead" :loading="markAllLoading">
          全部已读
        </el-button>
      </div>
      <el-alert
        type="info"
        :closable="false"
        show-icon
        class="notice-alert"
      >
        <span>消息15天后自动清除</span>
      </el-alert>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="消息类型">
          <el-select v-model="searchForm.type" placeholder="选择消息类型" clearable style="width:240px">
            <el-option label="全部" value=""></el-option>
            <el-option label="看房预约" value="system-appointment"></el-option>
            <el-option label="订单通知" value="system-order"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 消息列表 -->
    <div class="message-list" v-loading="loading">
      <el-timeline>
        <el-timeline-item
          v-for="message in filteredMessages"
          :key="message.id"
          :type="getTimelineType(message.type)"
          :icon="getMessageIcon(message.type)"
          :hollow="message.status === '1'"
        >
          <el-card class="message-card" :class="{ 'is-read': message.status === '1' }">
            <div class="message-header">
              <div class="message-type">
                {{ getNoticeTypeText(message.type) }}
              </div>
              <div class="message-status" v-if="message.status === '0'">
                <el-tag size="small" type="danger">未读</el-tag>
              </div>
            </div>
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-footer">
              <div class="message-time">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(message.createTime) }}</span>
              </div>
              <el-button 
                v-if="message.status === '0'"
                type="text" 
                size="small"
                @click="markMessageAsRead(message)"
                :loading="message.loading"
              >
                标记已读
              </el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <!-- 空状态 -->
      <el-empty 
        v-if="filteredMessages.length === 0" 
        description="暂无消息" 
        :image-size="200"
      />
    </div>

    <!-- 分页器 -->
    <div class="pagination-container" v-if="filteredMessages.length">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Bell, ChatDotRound, Calendar, Setting, Warning, InfoFilled, Clock } from '@element-plus/icons-vue';
import request from "../../utils/request";
import dayjs from 'dayjs';
import { loadUnreadCount } from '../../utils/messageUtils';

const data = reactive({
  user: JSON.parse(localStorage.getItem('localStorageUser')),
});

const router = useRouter();
const loading = ref(false);
const noticeList = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const markAllLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  type: ''
});

// 获取系统通知
const getSystemNotices = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    };
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const res = await request.get('/messages/selectAll');
    if (res.code === '200') {
      noticeList.value = res.data.items || [];
      total.value = res.data.total || 0;
      
      // 更新已读状态
      // updateMessageStatus();
    }
  } catch (error) {
    console.error('获取系统通知失败:', error);
    ElMessage.error('获取系统通知失败');
  } finally {
    loading.value = false;
  }
};

// 更新单个消息已读状态
// const updateMessageStatus = async () => {
//   try {
//     await request.put(`/messages/markAsRead?&receiverId=${data.user.id}&receiverType=${data.user.role}`);
//   } catch (error) {
//     console.error('更新消息状态失败:', error);
//   }
// };

// 标记单个消息为已读
const markMessageAsRead = async (message) => {
  message.loading = true;
  try {
    await request.put(`/messages/markAsRead?receiverId=${data.user.id}&receiverType=${data.user.role}&messageId=${message.id}`);
    ElMessage.success('消息已标记为已读');
    getSystemNotices();
    // 更新未读消息数量
    await loadUnreadCount(data.user.id, data.user.role);
  } catch (error) {
    console.error('标记消息已读失败:', error);
    ElMessage.error('标记消息已读失败');
  } finally {
    message.loading = false;
  }
};

// 标记所有消息为已读
const markAllAsRead = async () => {
  markAllLoading.value = true;
  try {
    await request.put(`/messages/markAllAsRead?receiverId=${data.user.id}&receiverType=${data.user.role}`);
    ElMessage.success('所有消息已标记为已读');
    getSystemNotices();
    // 更新未读消息数量
    await loadUnreadCount(data.user.id, data.user.role);
  } catch (error) {
    console.error('标记全部已读失败:', error);
    ElMessage.error('标记全部已读失败');
  } finally {
    markAllLoading.value = false;
  }
};

// 获取消息类型图标
const getMessageIcon = (type) => {
  switch (type) {
    case 'system-appointment':
      return Calendar;
    case 'system-order':
      return Bell;
    default:
      return InfoFilled;
  }
};

// 获取时间线类型
const getTimelineType = (type) => {
  switch (type) {
    case 'system-appointment':
      return 'primary';
    case 'system-order':
      return 'info';
    default:
      return 'success';
  }
};

// 获取通知类型文本
const getNoticeTypeText = (type) => {
  const typeMap = {
    'system-appointment': '看房预约',
    'system-order': '订单通知',
    // 可以根据实际情况添加更多类型
  };
  return typeMap[type] || '系统消息';
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 筛选后的消息列表
const filteredMessages = computed(() => {
  if (!searchForm.type) {
    return noticeList.value;
  }
  return noticeList.value.filter(item => item.type === searchForm.type);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getSystemNotices();
};

// 重置表单
const resetForm = () => {
  searchForm.type = '';
  currentPage.value = 1;
  getSystemNotices();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getSystemNotices();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getSystemNotices();
};



onMounted(() => {
  getSystemNotices();
});
</script>

<style scoped>
.message-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  margin: 0 0 16px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.notice-alert {
  margin-bottom: 20px;
}

.filter-container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.message-list {
  padding: 0;
  background-color: transparent;
  border-radius: 8px;
}

.message-card {
  margin-bottom: 16px;
  transition: all 0.3s;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.message-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-card.is-read {
  opacity: 0.8;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.message-type {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.message-content {
  color: #606266;
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
  margin-bottom: 16px;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px dashed #ebeef5;
}

.message-time {
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.message-time .el-icon {
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-page {
    padding: 15px;
  }
  
  .filter-container {
    padding: 15px;
  }
}

/* 自定义时间线样式 */
:deep(.el-timeline) {
  padding-left: 0;
}

:deep(.el-timeline-item__tail) {
  border-left: 2px solid #e4e7ed;
}

:deep(.el-timeline-item__node--normal) {
  left: -1px;
}

:deep(.el-timeline-item__wrapper) {
  padding-left: 20px;
}
</style>